<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视频播放</title>
</head>
<body>
    <p>
        <button>换电影</button>
    </p>
    <video controls="controls"></video>
    <script>
        let playing = false
        const video = document.querySelector('video')
        let currentTime = video.currentTime
        const setState = function (p = playing) {
            let fetch_url =  '/api/currentTime?'
            let need_fetch = false
            if (p != playing) {
                playing = p
                fetch_url += `playing=${playing}&`
                need_fetch = true
            }
            if (Math.abs(currentTime - video.currentTime) > .5) {
                currentTime = video.currentTime
                fetch_url += `time=${video.currentTime}&`
                need_fetch = true
            }
            if (need_fetch) {
                fetch(fetch_url, { cache: 'no-cache' })
            }
        }
        video.addEventListener('play', function () {
            currentTime = video.currentTime
            setState(true)
        })
        video.addEventListener('pause', function () {
            currentTime = video.currentTime
            setState(false)
        })
        video.addEventListener('waiting', function () {
            currentTime = video.currentTime
            setState(false)
        })
        video.addEventListener('timeupdate', function () {
            setState()
        })

        const sse = new EventSource('/sse/currentTime')
        sse.addEventListener('message', e => {
            const data = JSON.parse(e.data)
            if (typeof data?.playing != 'undefined') {
                currentTime = data.currentTime
                playing = data.playing

                if (video.src != data.src) {
                    video.src = data.src
                }
            
                if (playing) {
                    video.play()
                } else {
                    video.pause()
                }
                if (Math.abs(currentTime - video.currentTime) > 1.5) {
                    video.currentTime = currentTime
                }
            }
        })
        
        document.querySelector('button').addEventListener('click', function () {
            const src = prompt('请输入完整的视频文件URL,\n需要当前浏览器支持解码, \n建议MP4')?.trim()
            if (src) {
                fetch('/api/changeSrc', {
                    headers: { 'Content-Type': 'application/json' },
                    method: 'POST',
                    body: JSON.stringify({ src })
                })
            }
        })
    </script>
</body>
</html>